package com.tool_stdy.concurrent;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by yan_li on 2016/1/24.
 */
public class CyclicBarrierTest implements Runnable {
    private static CyclicBarrier cycli = new CyclicBarrier(5,new TestRun());
    private String name;
    @Override
    public void run() {
        try {
            System.out.println(Thread.currentThread().getName()+"--到达");
            cycli.await();
            System.out.println(Thread.currentThread().getName()+"--任务Done");
            cycli.await();
        } catch (InterruptedException e) {
           // e.printStackTrace();
            System.out.println(Thread.currentThread().getName()+"--被中断!!!");
        } catch (BrokenBarrierException e) {
           // e.printStackTrace();
            System.out.println(Thread.currentThread().getName()+"-栅栏被破坏!!!");
        }
    }

    public static void main(String[] args) {
        ExecutorService exec = Executors.newFixedThreadPool(10);
        CyclicBarrierTest test = new CyclicBarrierTest();
        for(int i=0;i<10;i++){
            Thread t1 = new Thread(test);
            //exec.submit(test);
            t1.start();
            if(i==8){
                t1.interrupt();
            }
        }
    }
}
 class TestRun implements Runnable{
    public boolean flag =false;
    @Override
    public void run() {
        if(flag){
            System.out.println(Thread.currentThread().getName()+" 任务完成..");
        }
        else {
            System.out.println(Thread.currentThread().getName()+" 集合完毕!");
            flag = true;
        }
    }
}
